package org.orr.budgetpro.services;

import org.orr.budgetpro.dao.BudgetDAO;
import org.orr.budgetpro.entities.Budget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BudgetService {
	@Autowired
	private BudgetDAO budgetDAO;

	@Transactional
	public Budget getBudget(Integer budgetId) {
		Budget budget = budgetDAO.getBudget(budgetId);
		fetchCollections(budget);

		return budget;
	}

	@Transactional
	public Budget getBudgetByUserId(String userId) {
		Budget budget = budgetDAO.getBudgetByUserId(userId);
		fetchCollections(budget);

		return budget;
	}

	private void fetchCollections(Budget budget) {
		// Workaround to simulate EAGER fetch on more than one bag collection;
		// otherwise, we get
		// "org.hibernate.HibernateException: cannot simultaneously fetch multiple bags"
		budget.getExpenseItems().size();
	}

	@Transactional
	public void saveBudget(Budget budget) {
		budgetDAO.saveBudget(budget);
	}

	@Transactional
	public void deleteIncomeItem(Integer incomeItemId) {
		budgetDAO.deleteIncomeItem(incomeItemId);
	}

	@Transactional
	public void deleteExpenseItem(Integer expenseItemId) {
		budgetDAO.deleteExpenseItem(expenseItemId);
	}

	@Transactional
	public boolean userOwnsBudget(Integer budgetId, String userId) {
		Budget budget = budgetDAO.getBudget(budgetId);

		return budget.getUser().getUserId().equals(userId);
	}
}
